package sunsun.xiaoli.jiarebang;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.StrictMode;
import android.provider.Settings;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.itboye.pondteam.app.MyApplication;
import com.itboye.pondteam.base.LingShouBaseActivity;
import com.itboye.pondteam.utils.Const;
import com.itboye.pondteam.utils.SPUtils;
import com.itboye.pondteam.utils.udp.VersionUtil;
import com.itboye.pondteam.volley.ResultEntity;
import sunsun.xiaoli.jiarebang.app.App;
import sunsun.xiaoli.jiarebang.beans.UpdateVersionBean;
import sunsun.xiaoli.jiarebang.device.DeviceActivity;
import sunsun.xiaoli.jiarebang.device.LoginActivity;
import sunsun.xiaoli.jiarebang.logincontroller.LoginController;
import sunsun.xiaoli.jiarebang.logincontroller.LoginedState;
import sunsun.xiaoli.jiarebang.logincontroller.UnLoginState;
import sunsun.xiaoli.jiarebang.utils.SpContants;
import sunsun.xiaoli.jiarebang.utils.UpdateManager;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 日志名  格式   android_用户ID_yyyy-MM-dd
 *
 * @author young
 */
public class SplashActivity extends LingShouBaseActivity implements UpdateManager.ICompleteListenner, Observer {

    Handler handler;
    boolean hasLogined = false;
    ImageView img_splash;
    App mApp;
    private boolean isFirstInstall;
    private AlertDialog dialog;

    //强制更新
    private boolean isDownload = false;
    private UpdateManager manager;
    private String roomId;
    int count = 0;
    private String bannerUrl = "";
    private String webTitle = "";
    private String jumpUrl = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initData() {
        initPhotoError();
        mApp = (App) getApplication();
        if (getPackageName().contains("pondlink")) {
            img_splash.setImageResource(R.drawable.pondlink_splash);
        }
        try {
            isFirstInstall = (boolean) SPUtils.get(this, null, Const.IS_FIRST, true);
            hasLogined = (boolean) SPUtils.get(this, null, Const.IS_LOGINED, false);
        } catch (Exception e) {

        }
        img_splash.setOnClickListener(view -> {
            count++;
            if (count >= 5) {
                MyApplication.getInstance().isDebug = true;
            } else {
                MyApplication.getInstance().isDebug = false;
            }
        });
    }

    private void initPhotoError() {
        // android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }


    /**
     * 打开 APP 的详情设置
     */
    private void openAppDetails() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("备份通讯录需要访问 “通讯录” 和 “外部存储器”，请到 “应用信息 -> 权限” 中授予！");
        builder.setPositiveButton("去手动授权", (dialog, which) -> {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setData(Uri.parse("package:" + getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            startActivity(intent);
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    //    以下代码可以跳转到应用详情，可以通过应用详情跳转到权限界面(6.0系统测试可用)
    private void getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction(Intent.ACTION_VIEW);
        localIntent.setClassName("com.android.settings", "com.android.settings.SubSettings");
        localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        startActivity(localIntent);
    }

    private String paserTime(long milliseconds) {
        System.setProperty("user.timezone", "Asia/Shanghai");
        TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
        TimeZone.setDefault(tz);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String times = format.format(new Date(milliseconds));

        return times;
    }

    private void startTimer() {
        handler = new Handler() {
            public void handleMessage(android.os.Message msg) {

                if (hasLogined) {
                    LoginController.setLoginState(new LoginedState());
                    startActivity(new Intent(getApplicationContext(), DeviceActivity.class));
                } else {
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                }

                finish();
            }
        };
        handler.sendEmptyMessageDelayed(123, 2500);
    }



    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        checkVersionUpdate(false);
    }

    private void checkVersionUpdate(boolean isCheck) {
        if (isCheck) {

            //添加更新
            List<UpdateVersionBean.Url> list = new ArrayList<>();
            list.add(new UpdateVersionBean.Url("版本号1.0.0", "https://62f8def9062d8fbb10f9a63f8602d604.dd.cdntips.com/imtt.dd.qq.com/16891/AD45CA32F51628428A410E03184B61EF.apk?mkey=5c11d1c170107b89&f=8935&fsname=com.itboye.lingshou_1.4.2_142.apk&csr=1bbd&cip=112.16.93.124&proto=https"));
            UpdateVersionBean updateVersionBean = new UpdateVersionBean("1.0.0", "更新版本吧", list);

            String appType = getPackageName();
            if (isFirstInstall && (appType.toLowerCase().contains("pondteam".toLowerCase()) || appType.toLowerCase().contains("pondlink".toLowerCase()))) {
                showXieYiForPondTeam();
            } else {
                if (!VersionUtil.getVersionCode().equals(updateVersionBean.getVersion())) { //更新
                    onManager(updateVersionBean);
                } else {
                    startTimer();
                }
            }


        } else {
            startTimer();
        }
    }

    void showXieYiForPondTeam() {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        View view = View.inflate(this, R.layout.alert_use_note, null);
        alert.setView(view);
        dialog = alert.show();

        ((TextView) view.findViewById(R.id.tv_note)).setText(getClickableSpan());
        ((TextView) view.findViewById(R.id.tv_note)).setMovementMethod(LinkMovementMethod.getInstance());
        view.findViewById(R.id.tv_ok).setOnClickListener(this);
        view.findViewById(R.id.tv_cancel).setOnClickListener(this);
    }

    private SpannableString getClickableSpan() {
        //监听器
        View.OnClickListener listener = v -> {
            Uri uri = Uri.parse(Const.PONDLINK_XIYI_URL);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        };
        SpannableString spanableInfo = new SpannableString(Html.fromHtml(getString(R.string.xieyi)));
        int start = Html.fromHtml(getString(R.string.xieyi)).toString().indexOf("http");  //超链接起始位置
        int end = Html.fromHtml(getString(R.string.xieyi)).toString().length() - 1;   //超链接结束位置
        //可以为多部分设置超链接
        spanableInfo.setSpan(new Clickable(listener), start, end, Spanned.SPAN_MARK_MARK);
        return spanableInfo;
    }

    //更新完成
    @Override
    public void onSuccess() {

        if (isDownload) {
            if (manager != null) {
                manager.installApk();
            } else {
                this.finish();
            }
        } else {
            startTimer();
        }
    }

    //取消更新
    @Override
    public void onClose() {
        if (isDownload) {
            this.finish();
        } else {
            startTimer();
        }
    }

    @Override
    public void update(Observable observable, Object o) {
        ResultEntity entity = handlerError(o);
        if (entity != null) {
            if (entity.getCode() != 0) {

            }
        }
    }

    class Clickable extends ClickableSpan implements View.OnClickListener {
        private final View.OnClickListener mListener;

        public Clickable(View.OnClickListener listener) {
            mListener = listener;
        }

        @Override
        public void onClick(View view) {
            mListener.onClick(view);
        }

    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        if (handler != null) {
            handler.removeMessages(123);
        }
        finish();
    }

    @Override
    public void finish() {
        // TODO Auto-generated method stub
        super.finish();
//		overridePendingTransition(0, R.anim.anim_falldown);
    }

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        if (view.getId() == R.id.tv_ok) {
            SPUtils.put(SplashActivity.this, null, Const.IS_FIRST, false);
            startTimer();
            dialog.dismiss();
        } else if (view.getId() == R.id.tv_cancel) {
            dialog.dismiss();
            SPUtils.put(SplashActivity.this, null, Const.IS_FIRST, true);
            finish();
        }
    }


    //更新弹框
    public void onManager(UpdateVersionBean appUpdateBean) {
        manager = new UpdateManager(this, this,
                appUpdateBean.getUpdate_log() + "",
                appUpdateBean.getDownload_url().get(0).getValue(), appUpdateBean.getVersion(), isDownload);
        manager.checkUpdateInfo();
    }

}
